package cn.com.pc.content.event;

import cn.com.pc.content.service.es.ESCurdService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.rest.RestStatus;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class TagListener {

    private final ESCurdService esCurdService;

    @SneakyThrows
    @Async
    @EventListener(TagEvent.class)
    public void saveTag(TagEvent event) {
        String name = event.name();
        Object source = event.getSource();
        Map<String, Object> params = event.params();
        String id = (String) params.get("id");
        String indexName = (String) params.get("indexName");

        switch (name) {
            case "createTag":{
                RestStatus restStatus = esCurdService.insertWithId(indexName, id, source);
                if (RestStatus.CREATED != restStatus && RestStatus.OK != restStatus) {
                    log.error("{} 标签创建索引失败:{}", restStatus, source);
                }
                break;
            }
            case "updateTag":{
                RestStatus restStatus = esCurdService.update(indexName, id, source);
                if (RestStatus.OK != restStatus) {
                    log.error("标签修改索引失败:{}", source);
                }
                break;
            }
            case "deleteTag":{
                RestStatus restStatus = esCurdService.deleteDoc(indexName, id);
                if (RestStatus.OK != restStatus) {
                    log.error("标签删除索引失败:{}", source);
                }
                break;
            }
        }
    }
}